import React, { useState } from 'react';
import { useImmer } from 'use-immer';
import { Button, Divider } from "antd";
import './immer.less';

function Immer() {
  const [list, setList] = useImmer([]);
  const [data, setData] = useImmer({ num: 0 });
  const [ userInfo, setUserInfo ] = useState(['dell']);
  const [ user, setUser ] = useState({ name: 'John', age: 17 });

  const handlerArr = () => {
    const newArr = [...userInfo];
    newArr[0] = 'Nancy';
    setUserInfo(newArr);
  };
  const handlerObejct = () => {
    const newObj = {...user};
    newObj.name = 'Clark';
    setUser(newObj);
  };
  const handlerOtherObject = () => {
    setData((draft) => {
      draft.num = data.num + 1;
    });
  };
  const handlerOtherArray = () => {
    setList((draft) => {
      // draft[0] = draft[0] + 1;
      draft.push(draft.length);
    });
  };

  return (
    <div className="common-ele">
      <Divider />
      <h3>基础: 修改引用类型变量元素的值</h3>
      <Button onClick={handlerArr}>修改数组元素</Button>
      <div>{ userInfo[0] }</div>
      <Button onClick={handlerObejct}>修改对象属性</Button>
      <div>{ user.name }</div>
      <Button onClick={handlerOtherArray}>修改数组元素的另一种方式</Button>
      {
        /*<div>{ list[0] }</div>*/
        list.length
      }
      <Button onClick={handlerOtherObject}>修改对象属性的另一种方式</Button>
      <div>{ data.num }</div>
      <Divider />
    </div>
  )
}

export default Immer;